<script lang="ts" setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import { toNumber } from 'lodash-es'
import { DeleteLabel, GetData } from '@/api/modules/clientAccountLabel.ts'
import { GetOptionData } from '@/api/modules/clientAdminAccount.ts'

const router = useRouter()

const inquireFrom = reactive({
  LabelName: '',
  LabelType: '',
  AdminId: '',
})
const dataList: any = ref([])
// 加载
const loading = ref(false)
const total = ref(0) // 总数据数
let PageSize = 10 // 每页条数
let PageNum = toNumber(localStorage.getItem('currentPage')) || 1

const optionData: any = ref([])

// 获取数据
function GetDataList(PageIndex: number = 1, PageSize: number = 10) {
  loading.value = true
  const params = {
    PageIndex,
    PageSize,
    ...(inquireFrom.LabelName && { LabelName: inquireFrom.LabelName }),
    ...(inquireFrom.LabelType && { LabelType: inquireFrom.LabelType }),
    ...(inquireFrom.AdminId && { AdminId: inquireFrom.AdminId }),
  }
  GetData(params).then(async (res: any) => {
    if (res.succeeded) {
      dataList.value = res.data.items
      total.value = res.data.total
      loading.value = false
      const optionList = await GetOptionData()
      optionData.value = optionList.data
    }
    else {
      ElMessage.error('查询失败')
      loading.value = false
    }
  })
}

// 查询
function Inquire() {
  GetDataList(1, PageSize)
}

// 添加
function AddEvent() {
  router.push({
    name: 'clientAccountLabelDetail',
  })
}

// 编辑
function Redact(message: any) {
  localStorage.setItem('currentPage', `${PageNum}`)
  router.push({
    name: 'clientAccountLabelDetail',
    query: {
      id: message.id,
    },
  })
}

// 删除
function Delete(row: any) {
  ElMessageBox.confirm(
    '确定要删除该标签吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      DeleteLabel(row.id).then((res: any) => {
        if (res.succeeded) {
          ElMessage.success('删除成功')
          GetDataList()
        }
        else {
          ElMessage.error('删除失败')
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

// 页码
function handleSizeChange(val: number) {
  GetDataList(1, val)
  PageSize = val
}
function handleCurrentChange(val: number) {
  GetDataList(val, PageSize)
  PageNum = val
}

const nowPageNum = computed(() => {
  return toNumber(localStorage.getItem('currentPage')) || 1
})

onMounted(() => {
  if (localStorage.getItem('currentPage') !== null) {
    GetDataList(toNumber(localStorage.getItem('currentPage')), 20)
    localStorage.removeItem('currentPage')
  }
  else {
    GetDataList()
  }
})
</script>

<template>
  <PageMain>
    <SearchBar :show-toggle="false">
      <div class="header">
        <el-form>
          <div class="from">
            <el-form-item label="标签名">
              <el-input v-model="inquireFrom.LabelName" placeholder="请输入标签名" clearable @keyup.enter="Inquire" />
            </el-form-item>
            <el-form-item label="标签类型">
              <el-select v-model="inquireFrom.LabelType" placeholder="请选择" clearable>
                <el-option label="基础标签" :value="1" />
                <el-option label="需求偏好" :value="2" />
                <el-option label="销售标签" :value="3" />
                <el-option label="售后标签" :value="4" />
                <el-option label="自定义" :value="5" />
              </el-select>
            </el-form-item>
            <el-form-item v-if="toNumber(inquireFrom.LabelType) === 5" label="绑定角色">
              <el-select v-model="inquireFrom.AdminId" placeholder="请选择角色" clearable>
                <el-option v-for="item in optionData" :key="item.id" :label="item.realname" :value="item.id" />
              </el-select>
            </el-form-item>
          </div>
        </el-form>
        <div class="text-right">
          <el-button @click="Inquire">
            查询
          </el-button>
        </div>
      </div>
    </SearchBar>
    <ElDivider border-style="dashed" />
    <div class="mb-5 text-right">
      <el-button type="success" @click="AddEvent">
        添加
      </el-button>
    </div>
    <el-table v-loading="loading" :data="dataList" stripe style="width: 100%;" border>
      <el-table-column align="center" prop="id" label="id" width="200" />
      <el-table-column align="center" prop="adminId" label="登录账户id" width="200" />
      <el-table-column header-align="center" prop="labelName" label="标签名" width="300" />
      <el-table-column align="center" prop="labelType" label="标签类型" width="300">
        <template #default="scope">
          {{ scope.row.labelType === 1 ? '基础标签'
            : scope.row.roleId === 2 ? '需求偏好'
              : scope.row.roleId === 3 ? '销售标签'
                : scope.row.roleId === 4 ? '售后标签' : '自定义' }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" fixed="right" min-width="120">
        <template #default="scope">
          <div class="table-button">
            <el-button type="primary" @click="Redact(scope.row)">
              编辑
            </el-button>
            <el-button type="danger" @click="Delete(scope.row)">
              删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div style="height: 10px;" />
    <el-pagination
      :page-sizes="[5, 10, 20, 50, 100]"
      layout="total, sizes, ->, prev, pager, next, jumper"
      :total="total"
      :default-current-page="nowPageNum"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </PageMain>
</template>

<style scoped>
.header {
  display: grid;
  grid-template-columns: 6fr 1fr;
  grid-gap: 20px;

  .from {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    grid-gap: 20px;

    .el-form-item {
      margin-bottom: 0;
    }
  }
}
</style>
